<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新门店
      </el-button>
      <el-input
        v-model="sname"
        placeholder="门店名称"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
      />
      <el-input
        v-model="scode"
        placeholder="门店编号"
        style="width: 200px; margin-left: 10px"
        class="filter-item"
      />
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-search"
        @click="fetchData"
      >
        搜索门店
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        prop="code"
        label="门店编号"
        align="center"
        width="150"
      />
      <el-table-column
        prop="sname"
        label="门店名称"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="center"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            style="width: 100px"
            @click="handleUpdate(row.sname, row.code, row.id)"
          >
            输入
          </el-button>
          <el-button
            type="success"
            style="width: 100px"
            @click="showSheet(row.id, row.code, row.sname)"
          >
            成交道场
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    />

    <el-dialog
      class="kanyu-dialog"
      title="新门店"
      :visible.sync="dialogFormVisible"
      style="margin-top: -80px"
    >
      <el-form
        ref="dataForm"
        :model="salonObj"
        label-width="110px"
        style="margin-right: 30px"
        :rules="rules"
      >
        <el-form-item label="店铺全称" prop="sname">
          <el-input v-model="salonObj.sname" />
        </el-form-item>
        <el-form-item label="店家地址">
          <div style="display: grid">
            <el-cascader
              v-model="selectedOptions"
              :options="areaSelectData"
              style="width: 260px"
              :filterable="true"
              size="medium"
              @change="locationHandleChange"
            />
            <el-input
              v-model="addr2"
              autocomplete="off"
              style="width: 76%; margintop: 10px"
              placeholder="街道门牌号"
            />
          </div>
        </el-form-item>
        <!-- <el-form-item label="大B端">
          <el-input v-model="salonObj.bigbend" />
        </el-form-item> -->
        <el-form-item label="店铺业态">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="1">【生美】美睫美甲纹绣</el-checkbox>
            <el-checkbox label="2">【生美】面（头）部类</el-checkbox>
            <el-checkbox label="3">【生美】身体类</el-checkbox>
            <el-checkbox label="4">【生美】中医养生类</el-checkbox>
            <el-checkbox label="5">【生美】大健康类</el-checkbox>
            <el-checkbox label="6">【轻医美机构】</el-checkbox>
            <el-checkbox label="7">【综合医美机构】</el-checkbox>
            <el-checkbox label="8">【异业】服务女性的非美业</el-checkbox>
            <el-checkbox label="9">其他</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="店铺面积">
              <el-input-number
                v-model="salonObj.area"
                :min="1"
                :controls="false"
              />
              · 平米
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="店铺人数">
              <el-input-number
                v-model="salonObj.cnumber"
                :min="1"
                :controls="false"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="开发人员">
          <el-input v-model="salonObj.developer" />
        </el-form-item>
        <!-- <el-form-item label="沟通详情">
          <el-input
            v-model="salonObj.chat"
            :autosize="{ minRows: 1, maxRows: 2 }"
            type="textarea"
          />
        </el-form-item> -->
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="createSalon()"> 提交 </el-button>
      </div>
    </el-dialog>

    <el-dialog
      class="diag-dialog"
      title="."
      style="margin-top: 0"
      :visible.sync="dialogFormVisible2"
    >
      <el-row :gutter="20" style="margin: 0px 20px 10px;">
        <el-col
          :span="12"
          :offset="0"
          style="text-align: center"
        >门店名称：{{ diagname }}</el-col>
        <el-col
          :span="12"
          :offset="0"
          style="text-align: center"
        >门店编号：{{ diagcode }}</el-col>
      </el-row>
      <el-form
        ref="dataForm2"
        :model="kanyuObj"
        label-width="110px"
        style="margin-right: 30px"
        :rules="rules"
      >
        <el-row :gutter="0">
          <el-col :span="8" :offset="0">
            <el-form-item label="坐向" prop="position">
              <el-input v-model="kanyuObj.position" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="起始">
              <el-input v-model="kanyuObj.start" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="截至">
              <el-input v-model="kanyuObj.stop" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="外局优点">
          <el-checkbox-group v-model="checkedOutAdv">
            <el-checkbox v-for="(value, index) in outAdv" :key="index" :label="index">{{ value }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="外局缺点">
          <el-checkbox-group v-model="checkedOutDisadv">
            <el-checkbox v-for="(value, index) in outDisadv" :key="index" :label="index">{{ value }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="内局优点">
          <el-checkbox-group v-model="checkedInAdv">
            <el-checkbox v-for="(value, index) in inAdv" :key="index" :label="index">{{ value }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="内局缺点">
          <el-checkbox-group v-model="checkedInDisadv">
            <el-checkbox v-for="(value, index) in inDisadv" :key="index" :label="index">{{ value }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input
            v-model="kanyuObj.solution"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
          />
        </el-form-item>
        <el-row :gutter="0">
          <el-col :span="12" :offset="0">
            <el-form-item label="门店教练">
              <el-input v-model="kanyuObj.coach" />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="审核">
              <el-input v-model="kanyuObj.checker" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-upload
        style="text-align: center;"
        list-type="picture"
        action="/"
        :show-file-list="false"
        :limit="1"
        :before-upload="beforeUpload"
        :http-request="handleChange"
      >
        <el-button size="medium" type="primary" style="width: 150px;">上传户型图</el-button>
      </el-upload>
      <el-image
        v-if="kanyuObj.pic !== null && kanyuObj.pic !== undefined"
        layz
        style="width: 100%; height: 280px;margin-top: 20px;"
        :src="kanyuObj.pic"
        fit="contain"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible2 = false"> 取消 </el-button>
        <el-button type="primary" @click="updateDiag()"> 提交 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSalonList2, addSalon, saveKanyu, getKanyu } from '@/api/txs'
import { upload } from '@/api/base'
import { regionData, codeToText } from 'element-china-area-data'
import pinyin from 'js-pinyin'
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination'
import { getInAdv, getInDisadv, getOutAdv, getOutDisadv } from '@/utils/kanyu'

export default {
  components: { Pagination },
  data () {
    return {
      checkedOutAdv: [],
      checkedOutDisadv: [],
      checkedInAdv: [],
      checkedInDisadv: [],

      diagname: '',
      diagcode: '',
      sname: '',
      scode: '',
      position: '',

      total: 0,
      listQuery: {
        page: 1,
        limit: 10
      },

      checkList: [],
      location: '四川省成都市武侯区',
      selectedOptions: ['51', '5101', '510107'],
      addr2: '',
      areaSelectData: regionData,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      salonCode: 'SCCD' + dayjs().format('YYMMDD').slice(1),
      salonObj: {
        id: undefined,
        code: '',
        sname: '',
        address: '',
        area: 0,
        pic: '',
        stype: '',
        chat: '',
        developer: '',
        cnumber: 0,
        bigbend: '',
        isdiag: 0,
        createTime: new Date()
      },
      kanyuObj: {},
      list: null,
      listLoading: true,
      rules: {
        sname: [{ required: true, message: '必填项', trigger: 'blur' }],
        position: [{ required: true, message: '必填项', trigger: 'blur' }]
      }
    }
  },
  computed: {
    outAdv() {
      return getOutAdv()
    },
    outDisadv() {
      return getOutDisadv()
    },
    inAdv() {
      return getInAdv()
    },
    inDisadv() {
      return getInDisadv()
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    locationHandleChange () {
      this.location =
        codeToText[this.selectedOptions[0]] +
        codeToText[this.selectedOptions[1]] +
        codeToText[this.selectedOptions[2]]
      // // console.log(this.location)
      this.salonCode =
        pinyin.getCamelChars(codeToText[this.selectedOptions[0]]).slice(0, 2) +
        pinyin.getCamelChars(codeToText[this.selectedOptions[1]]).slice(0, 2) +
        dayjs().format('YYMMDD').slice(1)
    },
    fetchData () {
      this.listLoading = true
      getSalonList2(
        this.listQuery.page,
        this.listQuery.limit,
        this.sname,
        this.scode
      ).then(res => {
        this.list = res.data.data.records
        this.total = res.data.data.total
        this.listLoading = false
        // console.log(this.list)
      })
    },
    handleCreate () {
      this.salonObj = this.$options.data().salonObj
      this.checkList = []
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createSalon () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.salonObj)
          tempData.createTime = undefined
          tempData.address = this.location + '-' + this.addr2
          tempData.code = this.salonCode
          tempData.stype = this.checkList.join(' ')
          addSalon(tempData).then(res => {
            const d = res.data.data
            this.list.unshift(d)
            this.dialogFormVisible = false
            this.$notify({
              title: res.data.message,
              message: res.data.status,
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    handleUpdate (sn, sc, sid) {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.checkedOutAdv = []
      this.checkedOutDisadv = []
      this.checkedInAdv = []
      this.checkedInDisadv = []
      getKanyu(sid)
        .then(res => {
          this.kanyuObj = res.data.data
          this.kanyuObj.sid = sid
          if (this.kanyuObj.outadv) {
            this.checkedOutAdv = this.kanyuObj.outadv.split(',').map(Number)
          }
          if (this.kanyuObj.outdisadv) {
            this.checkedOutDisadv = this.kanyuObj.outdisadv.split(',').map(Number)
          }
          if (this.kanyuObj.inadv) {
            this.checkedInAdv = this.kanyuObj.inadv.split(',').map(Number)
          }
          if (this.kanyuObj.indisadv) {
            this.checkedInDisadv = this.kanyuObj.indisadv.split(',').map(Number)
          }
          loading.close()
          this.dialogFormVisible2 = true
          this.diagname = sn
          this.diagcode = sc
        })
        .catch(() => {
          this.$alert('获取信息故障，请联系管理员！', '服务器错误', {
            type: 'error',
            confirmButtonText: '确定'
          })
        })
      if (this.$refs.dataForm2) {
        this.$nextTick(() => {
          this.$refs['dataForm2'].clearValidate()
        })
      }
    },

    updateDiag () {
      this.$refs['dataForm2'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.kanyuObj)
          tempData.outadv = this.checkedOutAdv.join(',')
          tempData.outdisadv = this.checkedOutDisadv.join(',')
          tempData.inadv = this.checkedInAdv.join(',')
          tempData.indisadv = this.checkedInDisadv.join(',')
          saveKanyu(tempData)
            .then(_ => {
              this.dialogFormVisible2 = false
              this.$notify({
                title: 'Success',
                message: '提交成功',
                type: 'success',
                duration: 2000
              })
            })
            .catch(() => {
              this.$alert('提交失败，请联系管理员！', '服务器错误', {
                type: 'error',
                confirmButtonText: '确定'
              })
            })
        }
      })
    },

    showSheet (id, code, name) {
      this.$router.push({
        path: '/show/kanyu/' + id,
        query: {
          sname: name,
          scode: code
        }
      })
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传户型图要求 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小请不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // handleChange(file, fileList) {
    handleChange(options) {
      // console.log(options)
      const dataInfo = new FormData()
      dataInfo.append('file', options.file)
      upload(dataInfo).then((res) => {
        // console.log(res.data)
        this.kanyuObj.pic = res.data.data
        if (!this.kanyuObj.pic) {
          this.$notify({
            title: '失败',
            message: '请稍后重试，或联系管理员',
            type: 'error',
            duration: 2000
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.kanyu-dialog {
  .el-dialog {
    width: 100%;
  }
}
.diag-dialog {
  div.el-dialog {
    margin-top: 0 !important;
    width: 100%;
    height: 100%;
    background-color: rgb(239, 248, 255);
  }
  .el-dialog__header {
    padding: 0;
  }
  .el-dialog__title {
    color: #fff;
  }
  .el-dialog__body {
    padding: 0px 20px;
    height: 90vh;
    overflow: auto;
  }
  .el-dialog__footer {
    text-align: center;
  }
  .el-button {
    width: 40%;
  }
}
</style>
